package leetcode;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-11-14 12:43
 **/
public class LeetCode8 {

    public int myAtoi(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        int i = 0;
        int len = s.length();
        //边界
        int bound = Integer.MAX_VALUE / 10;
        //存储结果
        int res = 0;
        int sign = 1;
        while (s.charAt(i) == ' ') {
            if (++i == len) {
                return 0;
            }
        }
        if (s.charAt(i) == '-') {
            sign = -1;
        }
        if (s.charAt(i) == '+' || s.charAt(i) == '-') {
            i++;
        }
        for (int j = i; j < len; j++) {
            char temp = s.charAt(j);
            if (temp < '0' || temp > '9') {
                break;
            }
            if (res > bound || (res == bound && temp > '7')) {
                return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            res = res * 10 + (temp - '0');
        }
        return sign * res;
    }

}
